<template>
  <div id="viewContestView">
    <a-tabs default-active-key="questions" @tab-click="handleTabClick">
      <a-tab-pane key="questions" title="题目">
        <a-table
          :ref="qt_tableRef"
          :columns="qt_columns"
          :data="qt_dataList"
          class="question-tab"
        >
          <template #questionName="{ record }">
            <a-link @click="toQuestionPage(record.questionId)" color="cyan"
              >{{ record.questionVO.title }}
            </a-link>
          </template>
          <template #acceptNum="{ record }">
            <icon-user size="20" />
            x{{ record.questionVO.acceptedNum }}
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="standing" title="排行榜">
        <a-table
          :ref="sd_tableRef"
          :columns="sd_columns"
          :data="sd_dataList"
          :bordered="{ wrapper: true, cell: true }"
        >
          <template #AcInfo="{ record, column, rowIndex }">
            <div
              class="cell-content"
              @click="handleClick(rowIndex, column.title)"
            >
              <div
                v-if="getFirstAcTime(record.acInfo, column.title) >= '00:00'"
              >
                <div class="plus-icon">+</div>
                <div class="ac-time">
                  {{ getFirstAcTime(record.acInfo, column.title) }}
                </div>
              </div>
              <div
                v-else-if="getErrorCount(record.acInfo, column.title) != null"
                style="color: red"
              >
                ({{ getErrorCount(record.acInfo, column.title) }})
              </div>
            </div>
            <a-modal
              v-model:visible="visibleMap[`${rowIndex}-${column.title}`]"
              :mask-style="{ backgroundColor: 'rgba(0, 0, 0, 0.1)' }"
              :closable="false"
              :footer="null"
              class="custom-modal"
            >
              <div
                v-for="(item, index) of getItem(record.acInfo, column.title)"
                :key="index"
              >
                {{
                  moment
                    .utc(
                      moment
                        .duration(item.submitTime, "minutes")
                        .asMilliseconds()
                    )
                    .format("HH:mm")
                }}
                <span :style="getMessageColor(item.message)">{{
                  item.message
                }}</span>
                ->
                {{ item.submitId }}
              </div>
            </a-modal>
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="submit" title="我的提交">
        <a-table :ref="sb_tableRef" :columns="sb_columns" :data="sb_dataList">
          <template #message="{ record }">
            <span :style="getMessageColor(record.judgeInfo.message)">{{
              record.judgeInfo.message
            }}</span>
          </template>
          <template #createTime="{ record }">
            {{ moment(record.createTime).format("YYYY/MM/DD") }}<br />
            {{ moment(record.createTime).format("HH:mm:ss") }}
          </template>
          <template #questionVO="{ record }">
            <a-link @click="toQuestionPage(record.questionVO.id)"
              >{{ record.questionVO.title }}
            </a-link>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  ref,
  withDefaults,
  defineProps,
  onActivated,
  computed,
} from "vue";
import {
  ContestControllerService,
  QuestionControllerService,
  UserControllerService,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import moment from "moment/moment";
import { useRouter } from "vue-router";

const router = useRouter();
const loginUser = ref();
const qt_tableRef = ref();

const qt_dataList = ref([]);

const sd_tableRef = ref();

const sd_dataList = ref([]);

const sb_tableRef = ref();

const sb_dataList = ref([]);
const total = ref(0);
interface Props {
  contestId: number;
}

const visibleMap = ref({});

const getLoginUser = async () => {
  const res = await UserControllerService.getLoginUserUsingGet();
  if (res.code === 0) {
    loginUser.value = res.data;
  }
  return null;
};

const getMessageColor = computed(() => (message: string) => {
  if (message.includes("Accepted")) {
    return "color: green; font-size: 16px; margin: 0 10px;";
  } else if (message.includes("Waiting")) {
    return "color: grey; font-size: 16px; margin: 0 10px;";
  } else {
    return "color: red; font-size: 16px; margin: 0 10px;";
  }
});

const handleClick = (rowIndex, columnTitle) => {
  const key = `${rowIndex}-${columnTitle}`;
  visibleMap.value[key] = !visibleMap.value[key];
};

const getFirstAcTime = (acInfo: any, level: any) => {
  for (const item of acInfo) {
    if (item.level === level) {
      let formatTime;
      if (item.firstAcTime >= 0) {
        formatTime = moment
          .utc(moment.duration(item.firstAcTime, "minutes").asMilliseconds())
          .format("HH:mm");
      } else formatTime = "-1";

      return formatTime;
    }
  }
};

const getItem = (acInfo: any, level: any) => {
  for (const item of acInfo) {
    if (item.level === level) {
      console.log(item);
      return item.standingSubmitItems;
    }
  }
};

const getErrorCount = (acInfo: any, level: any) => {
  for (const item of acInfo) {
    if (item.level === level) {
      let errorCount = item.standingSubmitItems?.length || 0;
      if (errorCount === 0) return "";
      return errorCount * -1;
    }
  }
};
const props = withDefaults(defineProps<Props>(), {
  contestId: () => 0,
});

const qt_loadData = async () => {
  const res = await ContestControllerService.getQuestionListUsingGet(
    props.contestId as any
  );
  if (res.code === 0) {
    qt_dataList.value = res.data as any;
    console.log(sd_columns);
  } else {
    message.error("加载失败，" + res.message);
  }
};

const sd_loadData = async () => {
  const res = await ContestControllerService.getStandingListUsingGet(
    props.contestId as any
  );
  if (res.code === 0) {
    sd_dataList.value = res.data as any;
    total.value = res.data.length;
    console.log(sd_dataList);
  } else {
    message.error("加载失败，" + res.message);
  }
};
const sb_loadData = async () => {
  const res = await QuestionControllerService.listQuestionSubmitByPageUsingPost(
    {
      contestId: props.contestId as any,
      userId: loginUser.value ? loginUser.value.id : -1,
      sortField: "createTime",
      sortOrder: "descend",
    }
  );
  if (res.code === 0) {
    sb_dataList.value = res.data.records;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const handleTabClick = (key: string) => {
  if (key === "standing") {
    sd_loadData();
  }
  if (key === "submit") {
    sb_loadData();
  }
};
/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  qt_loadData();
  getLoginUser();
});

const qt_columns = [
  {
    dataIndex: "level",
  },
  {
    slotName: "questionName",
  },
  {
    slotName: "acceptNum",
  },
];
/**
 * 跳转到做题页面
 * @param id
 */
const toQuestionPage = (id: number) => {
  router.push({
    path: `/view/question/${id}`,
    query: { contestId: props.contestId },
  });
};
const sd_columns = computed(() => {
  const columns = [
    {
      title: "#",
      width: 40,
      render: ({ rowIndex }) => `${rowIndex + 1}`, // 使用索引加1作为"#"列的值
      align: "center", // 将该列设置为居中对齐
    },
    {
      title: "用户",
      dataIndex: "user.userName",
      width: 200,
    },
    {
      title: "=",
      dataIndex: "acNub",
      width: 40,
      align: "center", // 将该列设置为居中对齐
    },
    {
      title: "罚时",
      dataIndex: "penalty",
      width: 40,
      align: "center", // 将该列设置为居中对齐
    },
  ];

  // 根据qt_dataList.value中的数据动态添加列
  if (qt_dataList.value.length > 0) {
    const levels = new Set(qt_dataList.value.map((item) => item.level));
    levels.forEach((level) => {
      columns.push({
        title: level,
        slotName: `AcInfo`,
        width: 60,
        align: "center", // 将该列设置为居中对齐
      });
    });
  }
  return columns;
});
const sb_columns = [
  {
    title: "#",
    dataIndex: "id",
  },
  {
    title: "时间",
    slotName: "createTime",
  },
  {
    title: "用户",
    dataIndex: "userVO.userName",
  },
  {
    title: "题目",
    slotName: "questionVO",
  },
  {
    title: "编程语言",
    dataIndex: "language",
  },
  {
    title: "状态",
    slotName: "message",
  },
  {
    title: "时间(ms)",
    dataIndex: "judgeInfo.time",
  },
  {
    title: "内存(KB)",
    dataIndex: "judgeInfo.memory",
  },
];
</script>

<style>
#viewContestView {
  max-width: 1000px;
  margin: 0 auto;
}

#viewContestView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}

.question-tab {
  max-width: 700px;
  margin: 0 auto;
}

.arco-table-border-cell .arco-table-td {
  border-right-color: #ccc;
}

.cell-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.ac-time {
  font-size: 12px;
}

.plus-icon {
  color: green;
  font-size: 15px;
  line-height: 1;
}

.error-icon {
  color: red;
  font-size: 15px;
}

.custom-modal .arco-modal-content {
  width: 900px;
}

.custom-modal .arco-modal-body {
  min-height: 300px;
}
</style>
